package com.hsb.seckill.config;

import com.google.common.util.concurrent.RateLimiter;
import com.hsb.seckill.exception.GlobalException;
import com.hsb.seckill.result.ResBeanEnum;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * RateLimiter
 * 限流拦截器
 *
 */
public class RateLimiterInterceptor implements HandlerInterceptor {

    // 限速器
    private final RateLimiter rateLimiter;

    /**
     * 通过构造函数初始化限速器
     */
    public RateLimiterInterceptor(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    // 请求前置处理方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 成功获取令牌
        if (rateLimiter.tryAcquire()){
            return true;
        }
        // 获取令牌失败，返回提示信息
        throw new GlobalException(ResBeanEnum.ACCESS_LIMIT_REAHCED);
    }
}
